package com.cloudeasy.user.controller;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.oauth.JWT;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.user.constant.RoleConstant;
import com.cloudeasy.user.dto.ChangePasswordDTO;
import com.cloudeasy.user.dto.LoginDTO;
import com.cloudeasy.user.dto.RegisterDTO;
import com.cloudeasy.user.service.UserRoleService;
import com.cloudeasy.user.service.expand.EmailService;
import com.cloudeasy.user.service.expand.UserDetailService;
import com.cloudeasy.user.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class BaseController {

    private final EmailService emailService;

    private final UserService userService;

    private final UserRoleService userRoleService;

    private final UserDetailService userDetailService;

    public BaseController(EmailService emailService, UserService userService, UserRoleService userRoleService, UserDetailService userDetailService) {
        this.emailService = emailService;
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.userDetailService = userDetailService;
    }

    /**
     * 发送邮件验证码
     *
     * @param email 接受邮箱
     * @return {@link Result<Boolean>}
     */
    @PostMapping("/authCode/{email}")
    public Result<Boolean> sendAuthCode(@PathVariable("email") String email) {
        return ResultUtil.success(emailService.sendAuthCode(email));
    }

    /**
     * 注册
     *
     * @param registerDTO {@link RegisterDTO}
     * @return {@link Result<Boolean>}
     */
    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> register(@RequestBody @Validated RegisterDTO registerDTO) {
        String id = userService.register(registerDTO);
        if (id == null) {
            return ResultUtil.failure(ResultCodeEnum.PARAMETER_ERROR);
        }
        userRoleService.distribute(id, RoleConstant.DEFAULT_ROLE_ID);
        return ResultUtil.success();
    }

    /**
     * 登录
     *
     * @param loginDTO {@link LoginDTO}
     * @return {@link JWT}
     */
    @PostMapping("/login")
    public Result<JWT> login(@RequestBody @Validated LoginDTO loginDTO) {
        return ResultUtil.success(userDetailService.login(loginDTO));
    }

    /**
     * 修改密码
     *
     * @param changePasswordDTO {@link ChangePasswordDTO}
     * @return {@link Result<Boolean>}
     */
    @PutMapping("/reset")
    public Result<Boolean> resetPassword(@RequestBody @Validated ChangePasswordDTO changePasswordDTO) {
        return ResultUtil.success(userService.resetPassword(changePasswordDTO));
    }
}
